<script lang="ts" setup>
import { transformFormSchema, useAddEditForm, useAddEditFormModal } from '#/hooks/useAddEditForm'
import { $t } from '@vben/locales'
import { getAddEditFormSchema } from '../data/AddEditFrom'
import { PageApi } from '../use/api'
import { message } from 'ant-design-vue'
defineOptions({
    name: 'FormModelMenu'
})

const emit = defineEmits(['success', 'reload'])
const { Form, formApi, formTitle, setRowId, setViewMode } = useAddEditForm({
    title: '修改账号信息',
    onAddSubmit(values) {
        return PageApi.add(values)
    },
    onEditSubmit({ values, rowId }) {
        if(values.avatarUrl && values.avatarUrl instanceof File){
            const hide = message.loading('头像修改中，请勿关闭页面..', 0);
            PageApi.editAvatar(rowId,{file:values.avatarUrl}).then(()=>{
                hide()
                emit('reload')
                message.success('头像修改成功')
            })
        }
        return PageApi.edit(rowId, values)
    }
})

const { Modal, modalApi } = useAddEditFormModal({
    formApi,
    onOpen({ record, isViewMode = false }) {
        setViewMode(isViewMode)
        if (isViewMode) {
            modalApi.setState({
                showConfirmButton: false,
                cancelText: $t('common.close')
            })
        } else {
            modalApi.setState({
                showConfirmButton: true,
                cancelText: $t('common.cancel')
            })
        }
        setRowId(record?.id ?? null)

        const schema = getAddEditFormSchema()

        formApi.setState({
            // 更新表单数据
            schema: isViewMode ? transformFormSchema(schema) : schema
        })

        // 回填表单数据
        if (record) {
            if (record.assetsFrequentlyTraded) {
                record.assetsFrequentlyTraded = JSON.parse(record.assetsFrequentlyTraded)
            }
            formApi.setValues(record)
        }
    }
})

</script>
<template>
    <Modal :title="formTitle">
        <Form />
    </Modal>
</template>
